<?php
class Listing_Form_AddAnAdLocalForm extends Listing_Form_PostAnAddForm
{
    private $_category;
    private $_adid;
    private $_listing;
	public $img;
    
    
    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementDecorators = array(
        'ViewHelper',
        //'Errors',
    );

    protected $formDecorators = array(
            'PrepareElements',
            array('ViewScript', array('viewScript' => 'index/customization/add-an-ad-local.phtml'))
    );

    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
        array('HtmlTag', array('tag' => 'p', 'class' => 'price radio text')),
        array('Description', array('placement' => 'prepend', 'tag' => 'label')),
    );

    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'APPEND')),
    );
    
    protected $elementMultiCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementSelectDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
        array(array('row' => 'HtmlTag'), array('class'=>'select')),
    );
    
    protected $elementSelectDecorators1 = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
        array(array('row' => 'HtmlTag'), array('class'=>'select1')),
    );

    public function __construct($options = array())
    {
        $this->_category = !empty($options['category']) ? $options['category'] : array();
        $this->_adid = !empty($options['adid']) ? $options['adid'] : array();
        $this->_listing = !empty($options['listing']) ? $options['listing'] : new StdClass();
        $this->img = !empty($options['img']) ? $options['img'] : array();
        parent::__construct();
    }
    
    public function isValid($post = array())
    {
    	$post['tl_en'] = trim($post['tl_en']);
    	if($post['tl_en'] == '为收集添加一个标题'){
    		$post['tl_en'] = '';
    	}
    	
    	$post['pr'] = trim($post['pr']);
    	if($post['pr'] == '价格'){
    		$post['pr'] = '';
    	}
    	
   		$post['cs_en'] = trim($post['cs_en']);
    	if($post['cs_en'] == '写点有营养的介绍吧，使这次收集更加有意义。'){
    		$post['cs_en'] = '';
    	}
    	
    	$post['tags'] = trim($post['tags']);
    	if($post['tags'] == '多个标签用空格隔开'){
    		$post['tags'] = '';
    	}
    	
        $test1 = parent::isValid($post);
        $test2 = true;

        //Check the two validations
        if ($test1 & $test2){
            return true;
        }
        else {
            return false;
        }
    }
    
    public function init()
    {
        parent::init();
        $element = new Zend_Form_Element_Hidden('adid');
        $element->setValue((string) $this->_adid);
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        $this->addElement($element);
        
        $i = 0;
        foreach($this->_category  as $cat) {
            $i++;
            $element = new Zend_Form_Element_Hidden('category_link'.$i);
            $element->setValue((string) $cat->_id);
            $element->setDecorators(array(
                    'ViewHelper'
                )
            );
            $this->addElement($element);
        }
        $cat_str = '<ul>';
        foreach ($this->_category as $cat_id) {
            $cat_str .= '<li>';
            $tmp = array();            
            $category = Model_Category::find($cat_id->_id);
            foreach ($category->getParentTree() as $cat) {
                $tmp[] = $cat->name;
            }
            $cat_str .= implode(' > ', $tmp);
            $cat_str .= '</li>';
        }
        $cat_str .= '</ul>';
        $this->setDescription($cat_str);

        $this->addElement('text', 'tl_en', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '标题不足6个字')),
                array('StringLength', false, 6)
            ),
            'decorators' => $this->elementDecorators,
            'required' => true,
            'value' => isset($_POST['tl_en'])?$_POST['tl_en']:'为收集添加一个标题',
            'class' => isset($_POST['tl_en'])?($_POST['tl_en']=='为收集添加一个标题'?'listing-title listing-empty init_text':'listing-title init_text'):'listing-title listing-empty init_text'
        ));
		
        $this->addElement('text', 'pr', array(
            'validators' => array(
				array('Int', true, array('messages' => '仅能填写数字')),
				array('NotEmpty', true, array('messages' => '标题不足6个字'))
            ),
            'decorators' => $this->elementDecorators,
            'required' => true,
            'value' => isset($_POST['pr'])?$_POST['pr']:'价格',
            'class' => isset($_POST['pr'])?($_POST['pr']=='价格'?'listing-price listing-empty init_text':'listing-price init_text'):'listing-price listing-empty init_text'
        ));
        
        $this->addElement('textarea', 'cs_en', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '必须填写')),
            ),
            'decorators' => $this->elementDecorators,
            'cols' => '80',
            'required' => true,
            'label' => 'Description:',
            'value' => isset($_POST['cs_en'])?$_POST['cs_en']:'写点有营养的介绍吧，使这次收集更加有意义。',
            'id' => 'al-txa', 
            'class' => isset($_POST['cs_en'])?($_POST['cs_en']=='写点有营养的介绍吧，使这次收集更加有意义。'?'txa listing-empty init_text':'txa init_text'):'txa listing-empty init_text'
        ));
		
        $this->addElement('textarea', 'tags', array(
            'filters' => array('StringTrim'),
        	'validators' => array(
                array('NotEmpty', true, array('messages' => '必须填写')),
            ),
            'required' => true,
	        'decorators' => $this->elementDecorators,
	        'value' => isset($_POST['tags'])?$_POST['tags']:'多个标签用空格隔开',
	        'id' => 'al-tagsipt', 
	        'class' => isset($_POST['tags'])?($_POST['tags']=='多个标签用空格隔开'?'txa listing-empty init_text':'txa init_text'):'txa listing-empty init_text'
        ));
        
        $arr = array();
        $categories = Model_Category::getLevel1(array('post_an_ad' => 1, 'status' => Model_Category::STATUS_ACTIVE))->sort(array('pos' => 1));
        foreach ($categories as $cats)
        {
        	$arr[$cats->_id->__toString()] = $cats->name;
        }
        
        $this->addElement('hidden', 'category_specific', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请选择类目')),
            ),
            //'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            //'multiOptions' => $arr,
            'required' => true,
            'value' => isset($_POST['category_specific'])?$_POST['category_specific']:'',
            'rel' => isset($_POST['category_specific'])?Model_Category::find(new MongoId($_POST['category_specific']))->name:'点击选择', 
            //'class' => 'topcategory',
        ));
        
        $this->addElement('hidden', 'category_top', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请选择类目')),
            ),
        	'decorators' => $this->elementDecorators,
        	'required' => true,
            'value' => isset($_POST['category_top'])?$_POST['category_top']:'',
        ));
        
        $this->addElement('checkbox', 'weibocheckbox', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                
            ),
        	'decorators' => $this->elementDecorators,
            'checked' => 'checked',
        ));
        
        
        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['category'] = $this->_category;
        $opt['adid'] = $this->_adid;
        $opt['listing'] = $this->_listing;
        $opt['preview_link'] = $this->_preview_link;

        $this->getDecorator('ViewScript')->setOptions($opt);

    }

    public function save($preview = false)
    {
        if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }

        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            if ($user->role == Model_User::ROLE_ADMIN) {
                if(empty($ad->us)) {
                    $ad->user        = $user->_id;    
                }
            } else {
                $ad->user        = $user->_id;
            }
            if (empty($this->status)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
            }
        } else {
            $ad->status = 6;
        }
		
        //Requiered Attributs
        //$ad->tl_en          = (string)$_POST['tl_en'];
		
		$classname = Model_Listing::getInstanceClassname((array)$this->_listing->ca);
		$translateFields = $classname::getTranslationFormField();
		// echo $_POST['tl_en']; echo '<br>';
		// echo $_POST['cn_en']; echo '<br>';
		// echo $_POST['cs_en'];
		// print_r($translateFields);
		// exit;
		// $this->translate($ad, $translateFields, $classname);
		
		if (Zend_Registry::get('current_language') == 'en'){
			if ($ad->ad_type == -1) { 
				$ad->ad_type = Model_Listing::ORIGINAL_LANGUAGE_EN;
			}
			$ft = 'en';
			$tt = 'zh-TW';
			
			foreach($translateFields as $v => $r){
				$ad->{$v} = $this->getValue($v);
				
				if($v == 'cn_en'){
					if (empty($ad->{str_replace('en','tc', $v)})){
						$ad->{str_replace('en','tc', $v)} = $this->getValue($v);
					}
				} else {
					if (empty($ad->{str_replace('en','tc', $v)})){
						$ad->{str_replace('en','tc', $v)} = Ac_Translation::execute($this->getValue($v), $tt, $ft);
					}
				}
				
			}

		} else {
			if ($ad->ad_type == -1) {
				$ad->ad_type = Model_Listing::ORIGINAL_LANGUAGE_TC;
			}
			$ft = 'zh-TW';
			$tt = 'en';		
			
			foreach($translateFields as $v => $r){
				$ad->{str_replace('en','tc', $v)} = $this->getValue($v);
				
				if($v == 'cn_en'){
					if (empty($ad->{$v})){
						$ad->{$v} = $this->getValue($v);
					}
				} else {
					if (empty($ad->{$v})){
						$ad->{$v} = Ac_Translation::execute($this->getValue($v), $tt, $ft);
					}
				}
				

			}
		

		}

       // $ad->cn_en   = $_POST['cn_en'];
        $ad->employmenttype = $_POST['employmenttype'];
        $ad->salary         = $_POST['salary'];
        $ad->salary_hour    = $_POST['salary_hour'];
        //$key = array_search(-5, $_POST['residentstatus']);
        //if ($key !== false) {unset($_POST['residentstatus'][$key]);}
        //$ad->residentstatus = $_POST['residentstatus'];
        //$ad->careerlevel    = $_POST['careerlevel'];
        //$ad->joblocation    = $_POST['joblocation'];
        //$ad->description    = (string)$_POST['description'];
        
        //
        $ad->area_l1                   = new MongoId($POST['area_l1']);
        if ((string)$_POST['area_l1'] == ONLINE_ONLY_AREA) {
            $ad->area_l2 = new MongoId(ONLINE_ONLY_AREA);
        }
        elseif((string)$this->getValue('area_l1') == ENTIRE_CITY) {
            $ad->area_l2 = new MongoId(ENTIRE_CITY);
        }
        else {
            $ad->area_l2 = new MongoId($_POST['area_l2']);
        }

        //Optional Attributs
        if (!empty($_POST['educationlevel']))    {$ad->education          = (int)$_POST['educationlevel'];}
        if (!empty($_POST['yearexperience']))    {$ad->yearexperience     = (int)$_POST['yearexperience'];}
        //if (!empty($_POST['freshgraduate']))     {$ad->freshgraduate      = (int)$_POST['freshgraduate'][0];}
        //if (!empty($_POST['companybenefits']))   {$ad->companybenefits    = (array)$_POST['companybenefits'];}
        $ad->tl_sc 			= (string)$this->getValue('tl_en');
        $ad->cs_sc 			= (string)$this->getValue('cs_en');
        $ad->st_sc 			= (string)$this->getValue('st_en');
        //$ad->tag 			= (string)$this->getValue('tag');
		if (!empty($POST['tag']))         {$ad->tags         = array_values(explode(',',$_POST['tag']));}
        $ad->rmrk 			= (string)$this->getValue('remark');
        $ad->c_name 		= (string)$this->getValue('c_name');
        $ad->c_tel 			= (string)$this->getValue('c_tel');
        $ad->c_msn 			= (string)$this->getValue('c_msn');
        $ad->loc_flag = (string)$this->getValue('loc_flag');
        //$ad->agent = (string)$this->getValue('agent');
        
        foreach ((array) $_REQUEST['category'] as $cat) {
            $tmp = new MongoId($cat);
            $ad->addCategory($tmp);
        }

        $this->continueFillup();
        if (!$preview) {
            $ad = Model_Listing_Preview::saveAsListing($ad);
            Model_Listing_Preview::remove(array('_id' => $ad->_id));
        } else {
            //$ad = Model_Listing_Preview::convertFromListing($ad);
            $ad->forceSave();
        }
        return $ad;
    }
    
    public function saveA2C()
    {		
		$adid = $_SERVER['HTTP_ADID'];
    	if(!empty($_POST['ph'])){
			$_SERVER['NOT_JSON'] = 1;
			Ac_Util::uploadListingPhotoProcess();
		}
		
		if ($adid instanceof Model_Listing) {
			$listing = $adid;
		} else {
			$listing = Model_Listing_Preview::find(new MongoId($adid));
			if (empty($listing)) {
				$listing = Model_Listing::find(new MongoId($adid));
			}            
		}
		if(empty($listing->ph)){
			$error = new stdClass();
			$error->error = '至少上传一张图片';
			return $error;
		}
		
//		$user = Zend_Registry::get('loggedin_user');
		$a2c = new Model_A2c();
		$user = $a2c->postUserLogin('a2ctest_dev_vvxxkkgg@mail.com', '123456');
		$tag = explode(' ', $_POST['tags']);
		$tag = array_filter($tag);
		$a2c->postListing(
			Zend_Registry::get('current_language'), 
			$_POST['tl_en'], 
			$_POST['cs_en'], 
			$_POST['category_specific'], 
			$user->_id, 
			$user->session_id, 
			ENTIRE_CITY, 
			$listing->ph, 
			$_POST['pr'], 
			$privatekey = null, $url = null, $lat = null, $lon = null,
			$tag
		);
		return $a2c->result;
    }
	
    protected function continueFillup()
    {

    }

    public function populate(array $arr)
    {
        // if (empty($arr['title'])) {
            // $this->getElement('title')->setValue($this->_listing->title);
        // }
        if (Zend_Registry::get('current_language') == 'en'){
			$ft = 'en';
			$tt = 'zh-TW';
		} else {
			$ft = 'zh-TW';
			$tt = 'en';
		}

    }
	
	public function __toString()
    {
        $str = '
            $j("#area_l1").change(function (event) {                
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"area", f:"area_l2_postad", id: $j("#area_l1").val() },
                    function(data) {
                        $j("#area_l2").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#area_l2"));
                        });
                         //Entire City
					    if ($j("#area_l1").val() == "4eeae63be62d6c5978000000" || $j("#area_l1").val() == "4eeeeeeeeeeeeeeeeeeeeeee" || $j("#area_l1").val() == "4aaaaaaaaaaaaaaaaaaaaaaa") {
					        $j("#area_l2").hide();
					        $j("#st_en").hide();
					    }
					    else {
					        $j("#area_l2").show();
					        $j("#st_en").show();
					    }
                    });
           });
		   
        ';
		
		$str2 = '
			$j("tl_tc_back").click(function(event) {
			alert("test");
   
			});
		
		';
        $this->view->JQuery()->addJavascript($str);
		$this->view->JQuery()->addJavascript($str2);
        return parent::__toString();
    }
}
